package Day11.homework;

import java.util.concurrent.locks.ReentrantLock;

//使用公平锁ReentrantLock实现3个线程交替打印1-100的数字，
// 保证每个线程获取锁的机会均等
public class PrintNumber {
    int num = 100;
    int printNum = 0;
    ReentrantLock lock = new ReentrantLock(true);
    public void print(int i){
        String name = Thread.currentThread().getName();
        lock.lock();
        System.out.println(name+"打印"+i);
        lock.unlock();
    }

    public static void main(String[] args) {
        PrintNumber pn = new PrintNumber();
        for (int i = 1; i <= 3; i++) {
            new Thread(()->{
                while (pn.num>0){
                   pn.num--;
                   pn.printNum++;
                   pn.print(pn.printNum);
                }
            },"线程"+i).start();
        }
    }
}
